
package guoan.web.webCustomer;

import guoan.core.common.WebConfig;
import guoan.core.dto.RestResponse;
import guoan.domain.Customer;
import guoan.service.CustomerService;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.base.Preconditions;

@Controller
@RequestMapping("/webCustomer/login")
public class LoginController {
    protected final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private CustomerService customerService;

    /** 跳转到登陆页 */
    @RequestMapping(method = RequestMethod.GET)
    public String toLogin(){
        log.info(" [跳转到登陆页]开始");
        log.info(" [跳转到登陆页]结束");
        return "/webCustomer/login";
    }

    /** 登陆 */
    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public RestResponse<Boolean> doLogin(String uname, String upass, HttpSession session){
        log.info(" [登陆]开始");
        Preconditions.checkNotNull(uname, "请填写登陆帐号");
        Preconditions.checkNotNull(upass, "请填写登陆密码");

        // 登陆，返回客户信息
        Customer customer = customerService.login(uname, upass);
        // 登陆成功，则加入到session中
        if (customer != null) {
            session.setAttribute(WebConfig.SESSION_USER_KEY, customer);
            log.info(" [登陆]结束");
            return RestResponse.ok(true);
        } else {
            log.info(" [登陆]结束");
            return RestResponse.error("帐号或密码错误");
        }
    }

    /**
     * logout:登出系统. <br/>
     *
     * @author he.sun
     * @param session
     * @return
     */
    @RequestMapping(value="logout",method = RequestMethod.GET)
    public String logout(HttpSession session){
        log.info(" [登出系统]开始");

        Object customerObject = session.getAttribute(WebConfig.SESSION_USER_KEY);
        if (customerObject != null) {
            // 获取session中的客服信息
            Customer customer = (Customer) customerObject;
            log.debug("客服退出信息:{}", customer);
            session.invalidate();
        }
        log.info(" [登出系统]结束");

        // 跳转到登陆界面
        return "redirect:/webCustomer/login";
    }
}
